package com.sikadwa.analysis.util

import android.app.Application
import android.util.Log
import com.android.installreferrer.api.InstallReferrerClient
import com.android.installreferrer.api.InstallReferrerStateListener
import com.sikadwa.analysis.AnalysisBuilder
import com.sikadwa.analysis.bean.GoogleInstallBean
import com.sikadwa.analysis.http.HttpHelper
import com.sikadwa.analysis.http.UrlHelper
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlinx.coroutines.withContext
import kotlinx.coroutines.withTimeoutOrNull
import java.util.concurrent.atomic.AtomicBoolean
import kotlin.coroutines.resume

object GoogleInstallUtilV2 {

    /**
     * google play 返回的install referrer，
     * 建议每个接口都需要带上这个字段
     */
    private var _installReferrer: String = ""

    private val isInitializing = AtomicBoolean(false)

    /**
     * 初始化google install referrer 模块
     *
     * @param context Application
     */
    fun init(context: Application) {
        init(context) {
            saveS2sInfo()
        }
    }

    /**
     * 初始化google install referrer 模块
     *
     * @param context Application
     * @param success 成功回调
     */
    fun init(context: Application, success: (String) -> Unit) {
        // 如果已经初始化完成，直接回调
        if (_installReferrer.isNotBlank()) {
            success.invoke(getInstallReferrer())
            return
        }

        // 防止重复初始化
        if (isInitializing.getAndSet(true)) {
            return
        }

        // 使用独立的协程作用域，不需要手动管理生命周期
        CoroutineScope(Dispatchers.IO).launch {
            try {
                val referrer = initReferrerInBackground(context)
                _installReferrer = referrer
                isInitializing.set(false)

                withContext(Dispatchers.Main) {
                    success.invoke(getInstallReferrer())
                }
            } catch (e: Exception) {
                // 初始化失败，重置状态
                isInitializing.set(false)
                withContext(Dispatchers.Main) {
                    success.invoke(getInstallReferrer())
                }
            }
        }
    }

    /**
     * 挂起函数 在后台线程初始化 Referrer
     */
    private suspend fun initReferrerInBackground(context: Application): String {
        return withContext(Dispatchers.IO) {
            val referrerClient = InstallReferrerClient.newBuilder(context).build()
            setupReferrerConnection(referrerClient)
        }
    }

    /**
     * 将 InstallReferrer 连接转换为挂起函数
     */
    private suspend fun setupReferrerConnection(referrerClient: InstallReferrerClient): String {
        return suspendCancellableCoroutine { continuation ->
            referrerClient.startConnection(object : InstallReferrerStateListener {
                override fun onInstallReferrerSetupFinished(responseCode: Int) {
                    when (responseCode) {
                        InstallReferrerClient.InstallReferrerResponse.OK -> {
                            // 使用独立的协程，不需要管理生命周期
                            CoroutineScope(Dispatchers.IO).launch {
                                try {
                                    val referrer = withTimeoutOrNull(3000) {
                                        referrerClient.installReferrer?.installReferrer ?: ""
                                    } ?: ""
                                    referrerClient.endConnection()
                                    continuation.resume(referrer)
                                } catch (e: Exception) {
                                    referrerClient.endConnection()
                                    continuation.resume("")
                                }
                            }
                        }
                        InstallReferrerClient.InstallReferrerResponse.FEATURE_NOT_SUPPORTED -> {
                            Log.i("TAG", "FEATURE_NOT_SUPPORTED")
                            referrerClient.endConnection()
                            continuation.resume("")
                        }
                        InstallReferrerClient.InstallReferrerResponse.SERVICE_UNAVAILABLE -> {
                            Log.i("TAG", "SERVICE_UNAVAILABLE")
                            referrerClient.endConnection()
                            continuation.resume("")
                        }
                        else -> {
                            referrerClient.endConnection()
                            continuation.resume("")
                        }
                    }
                }

                override fun onInstallReferrerServiceDisconnected() {
                    Log.i("TAG", "InstallReferrerService disconnected")
                }
            })

            continuation.invokeOnCancellation {
                try {
                    referrerClient.endConnection()
                } catch (e: Exception) {
                    // 忽略异常
                }
            }
        }
    }

    /**
     * 获取Install Referrer
     * gclid123
     */
    fun getInstallReferrer(): String {
        return _installReferrer
    }

    /**
     * 保存google s2s信息
     */
    fun saveS2sInfo() {
        val url = UrlHelper.combineUrl()
        val path = AnalysisBuilder.pathGoogleInstall
        val body = GoogleInstallBean(
            channelCode = getInstallReferrer(),
            subChannelCode = getInstallReferrer()
        ).encrypt(path)
        HttpHelper.postData(url, body)
    }
}